# _ * _ coding:utf-8 _ * _

import tornado.web
from db import db
import re, base64, hashlib
import config
import datetime, os
from pymongo import ASCENDING, DESCENDING
from user import users

allowed = config.admin_users

# os.urandom(3).encode("hex")

class AdminBaseHandler(tornado.web.RequestHandler):
    def prepare(self):
        auth = self.request.headers.get('Authorization')
        authreq = False
        if auth is None:
            authreq = True
        else:
            auth = re.sub('^Basic ','',auth)
            username,password = base64.decodestring(auth).split(':')
            if (username, hashlib.md5(password).hexdigest()) not in allowed:
                authreq = True
        if authreq:
            self.set_header('WWW-Authenticate','Basic realm="09xg4"')
            self.set_status(401)
            self.finish()
            
class index(AdminBaseHandler):

    def get(self):
        acts = db.activities.find(sort=[["_id", DESCENDING]])
        self.render("admin_list.html", acts=acts)
        
class edit(AdminBaseHandler):
    
    def get(self, uuid):
        if uuid=="new":
            self.render("admin_edit.html", act={}, users=users, error=None)
        else:
            act = db.activities.find_one({"uuid":uuid})
            if not act:
                raise tornado.web.HTTPError(404)
            self.render("admin_edit.html", act=act, users=users, error=None)
            
    def post(self, uuid):
        act = dict(
            caption = self.get_argument("caption", ""),
            content = self.get_argument("content", ""),
            endtime = self.get_argument("endtime", ""),
            amount = self.get_argument("amount", ""),
        )
        for v in act.values():
            if not v:
                self.render("admin_edit.html", act=act, users=users, error=u"参数缺失！")
                return
        try:    
            datetime.datetime.strptime(act["endtime"], "%Y-%m-%d %H:%M:%S")
        except ValueError:
            self.render("admin_edit.html", act=act, users=users, error=u"截止时间格式错误！")
            return
        try:
            act["amount"] = int(act["amount"])
            if act["amount"]<0:
                self.render("admin_edit.html", act=act, users=users, error=u"名额输入错误！")
        except:
            self.render("admin_edit.html", act=act, users=users, error=u"名额输入错误！")
            return            
        
        if uuid=="new":
            act["appliers"] = []
            act["result"] = []
            act["uuid"] = os.urandom(3).encode("hex")
            db.activities.insert(act)
        else:
            act_old = db.activities.find_one({"uuid":uuid})
            if not act_old:
                raise tornado.web.HTTPError(404)
            db.activities.update({"uuid":uuid}, {"$set":act})
            
        self.redirect("/admin", True)
        
class delete(AdminBaseHandler):
    def get(self, uuid):
        db.activities.remove({"uuid":uuid})
        self.redirect("/admin")
        
class delete_applier(AdminBaseHandler):
    def get(self, uuid, applier):
        time = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
        time_str = time.strftime("%Y-%m-%d %H:%M:%S")
        ret = db.activities.update({"uuid":uuid, "appliers":applier, "endtime":{"$gt":time_str}}, {"$pull":{"appliers":applier}}, safe=True)
        if ret["updatedExisting"]:
            self.write("OK")
        else:
            self.write("error")
            
